# qrcode_uploader.py
import io
import qrcode
import requests

class QRCodeGenerator:
    """二维码生成器类"""
    def __init__(self, qrcode_url):
        self.qrcode_url = qrcode_url

    def generate_qr_code_to_blob(self):
        """
        生成二维码并将其转换为字节流（类似于 Blob）
        :return: 返回二维码的字节流
        """
        qr = qrcode.make(self.qrcode_url)
        byte_io = io.BytesIO()
        qr.save(byte_io, format='PNG')
        byte_io.seek(0)
        return byte_io


class FileUploader:
    """文件上传类"""

    def __init__(self, kintone_config):
        self.kintone_config = kintone_config

    def upload_file(self, file_name, file_blob):
        """
        上传文件
        :param file_name: 文件名
        :param file_blob: 文件内容（字节流）
        :return: 返回上传后的文件 key
        """
        try:

            url = self.kintone_config.file_upload_url  # 使用属性访问字典中的值

            files = {'file': (file_name, file_blob, 'image/png')}
            headers = {
                'X-Cybozu-API-Token': self.kintone_config.api_token,
                'X-Requested-With': 'XMLHttpRequest'
            }
            response = requests.post(url, headers=headers, files=files)

            response.raise_for_status()  # 如果响应码不是 2xx，抛出异常
            response_data = response.json()

            return response_data.get('fileKey')
        except requests.RequestException as e:
            print(f'Error in file upload: {e}')
        except Exception as e:
            print(f'Unexpected error: {e}')
        return None


def generate_and_upload_qrcode(kintone_config, qrcode_url):
    """生成二维码并上传文件，返回文件 key"""
    # 根据URL生成文件名
    if "alipay" in qrcode_url:
        file_name = "alipay_qr_img.png"
    else:
        file_name = "wx_qr_img.png"

    # print(f"qrcode_url: {qrcode_url}  File name: {file_name}")

    # 生成二维码
    qr_generator = QRCodeGenerator(qrcode_url)

    qr_blob = qr_generator.generate_qr_code_to_blob()
    # 文件上传
    uploader = FileUploader(kintone_config)
    file_key = uploader.upload_file(file_name, qr_blob)
    return file_key
